package com.tanhua.dubbo.server.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * * @title: TokenService
 *
 * @Author Philcan
 * @Date: 2021/8/15 18:07
 * @Version 1.0
 */
@Service
@Slf4j
public class TokenService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private static final String REDIS_KEY = "HX_TOKEN";
    @Autowired
    private HuanXinConfig huanXinConfig;

    public String getToken() {
        String token = this.redisTemplate.opsForValue().get(REDIS_KEY);
        if (StrUtil.isNotEmpty(token)) {
            return token;
        }
        return this.refreshToken();
    }

    public String refreshToken() {
        String targetUrl = this.huanXinConfig.getUrl() + this.huanXinConfig.getOrgName() + "/"
                + this.huanXinConfig.getAppName() + "/token";
        Map<String, Object> param = new HashMap<>();
        param.put("grant_type", "client_credentials");
        param.put("clientId", this.huanXinConfig.getClientId());
        param.put("client_secret", this.huanXinConfig.getClientSecret());
        HttpResponse response = HttpRequest.post(targetUrl).body(JSONUtil.toJsonStr(param)).timeout(20000).execute();
        if (!response.isOk()) {
            log.error("刷新token失败");
            return null;
        }
        String body = response.body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String token = jsonObject.getStr("access_token");
        if (StrUtil.isNotEmpty(token)) {
            long timeout = jsonObject.getLong("expires_in") - 3600;
            this.redisTemplate.opsForValue().set(REDIS_KEY, token, timeout, TimeUnit.SECONDS);
            return token;
        }
        return null;
    }
}
